﻿using System;
using System.Data;
using BLL;
using DAL;
using Ext.Net;

namespace ERP.Modules
{
    public partial class Report_Receipt : System.Web.UI.UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                GetReportReceipt();
                btnChooseReceipt.Disable(true);
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreReportReceipt_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtDateBeginFillter.Text = string.Empty;
            txtDateEndFillter.Text = string.Empty;
            GetReportReceipt();
        }
        protected void StoreReportReceipt_Detail_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            if (String.IsNullOrEmpty(txtReportReceipt_ID.Text))
            {
                GetReportReceiptReportDetailTemp();
            }
            else
            {
                if (_flag)
                {
                    GetReportReceiptReportDetailTemp();
                    GetReportReceiptReportDetailTempSum();
                }
                else
                {
                    GetReportReceiptReportDetail(int.Parse(txtReportReceipt_ID.Text));
                    GetReportReceiptReportDetailSum(int.Parse(txtReportReceipt_ID.Text));
                }
            }
        }
        protected void StoreReportReceiptOrder_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtDateBeginReceiptFillter.Text = string.Empty;
            txtDateEndReceiptFillter.Text = string.Empty;
            GetReceipt();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            GetAutoID();
            ClearText();
            btnRefreshReportReceiptCode.Enable(true);
            btnSavePopUp.Enable(true);
            btnAddMaterial.Enable(true);
            btnDelMaterial.Enable(true);
            var obj = new EtReportReceiptDetail { Users_Id = int.Parse(Session["Users_Id"].ToString()) };
            BllReportReceipt.DeleteTempAdd(obj);
            WindowsReportReceipt.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportReceipt.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    txtReportReceiptCode.ReadOnly = true;
                    txtReason.Text = string.Empty;
                    btnRefreshReportReceiptCode.Disable(true);
                    btnAddMaterial.Disable(true);
                    GetReportRceiptEdit(int.Parse(row.RecordID));
                    GetReportReceiptReportDetail(int.Parse(row.RecordID));
                    GetReportReceiptReportDetailSum(int.Parse(row.RecordID));
                    WindowsReportReceipt.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportReceipt.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtReportReceipt
                        {
                            ReportReceipt_ID = int.Parse(row.RecordID),
                        };
                        BllReportReceipt.Delete(obj);
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại chứng từ, không xoá được vui lòng xoá chứng từ trước !");
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetReportReceipt();
        }
        protected void btnFillter_Click(object sender, DirectEventArgs e)
        {
            GetReceiptFillterDateMain();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnAddMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grReceipt.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetReceipt();
            WindowReceipt.Show();
        }
        protected void btnDelMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportReceipt_Detail.GetSelectionModel() as CheckboxSelectionModel;
            var gridParam = e.ExtraParams["grReportReceipt_Detail"];
            var _dtGrid = JSON.Deserialize<DataTable>(gridParam);
            if (_dtGrid != null && _dtGrid.Rows.Count > 0)
            {
                foreach (DataRow rows in _dtGrid.Rows)
                {
                    if (sm != null)
                        foreach (var row in sm.SelectedRows)
                        {
                            try
                            {
                                if (_flag)
                                {
                                    var obj = new EtReportReceiptDetail
                                    {
                                        ReportDetail_Id = int.Parse(row.RecordID),
                                        Receipt_ID = int.Parse(rows["Receipt_ID"].ToString())
                                    };
                                    BllReportReceipt.DeleteTemp(obj);
                                }
                                else
                                {
                                    var obj = new EtReportReceiptDetail
                                    {
                                        ReportDetail_Id = int.Parse(row.RecordID),
                                        Receipt_ID = int.Parse(rows["Receipt_ID"].ToString()),
                                        Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                        ReportReceipt_ID = int.Parse(txtReportReceipt_ID.Text),
                                        Reason = txtReason.Text,
                                    };
                                    BllReportReceipt.DeleteDetail(obj);
                                }
                            }
                            catch (Exception ex)
                            {
                                HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                            }
                        }
                }
                GetReportReceiptReportDetailTemp();
                GetReportReceiptReportDetailTempSum();
                GetReportRceiptEdit(int.Parse(txtReportReceipt_ID.Text));
                GetReportReceiptReportDetailSum(int.Parse(txtReportReceipt_ID.Text));
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsReportReceipt.Close();
        }
        protected void btnRefreshReportReceiptCode_Click(object sender, DirectEventArgs e)
        {
            GetAutoID();
        }
        protected void btnChooseReceipt_Click(object sender, DirectEventArgs e)
        {
            InsertDetail();
        }
        protected void btnReportFillterReport_Click(object sender, DirectEventArgs e)
        {
            GetReceiptFillterDate();
        }
        //Double-Click
        protected void ReportReceiptDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            txtReportReceiptCode.ReadOnly = true;
            txtReason.Text = string.Empty;
            btnRefreshReportReceiptCode.Disable(true);
            btnAddMaterial.Disable(true);
            int ReportReceipt_ID = int.Parse(e.ExtraParams["ReportReceipt_ID"]);
            GetReportRceiptEdit(ReportReceipt_ID);
            GetReportReceiptReportDetail(ReportReceipt_ID);
            GetReportReceiptReportDetailSum(ReportReceipt_ID);
            WindowsReportReceipt.Show();
        }
        protected void ReportReceiptDetailDblClick(object sender, DirectEventArgs e)
        {
           
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {

        }
        //Menu
        protected void MenuItemExportExcel_Click(object sender, DirectEventArgs e)
        {

        }
        #endregion

        #region[Method]
        private void GetReportReceipt()
        {
            var _clsGetReport = new BllReportReceipt();
            var _dtGetReport = _clsGetReport.GetReportReceipt(txtSearch.Text);
            if (_dtGetReport != null && _dtGetReport.Rows.Count > 0)
            {
                StoreReportReceipt.DataSource = _dtGetReport;
                StoreReportReceipt.DataBind();
            }
            else
            {
                grReportReceipt.GetStore().RemoveAll();
            }
        }
        private void GetReportRceiptEdit(int id)
        {
            var _clsGetReportEdit = new BllReportReceipt();
            var _dtGetReportEdit = _clsGetReportEdit.GetReportReceiptEdit(id);
            if (_dtGetReportEdit != null && _dtGetReportEdit.Rows.Count > 0)
            {
                txtReportReceipt_ID.Text = _dtGetReportEdit.Rows[0]["ReportReceipt_ID"].ToString();
                txtReportReceiptCode.Text = _dtGetReportEdit.Rows[0]["ReportReceipt_Code"].ToString();
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportEdit.Rows[0]["Amount_Total"]).Replace(".", ",");
                txtDateBegin.Text = _dtGetReportEdit.Rows[0]["DateCreate"].ToString();
                txtNote.Text = _dtGetReportEdit.Rows[0]["Note"].ToString();
            }
        }
        private void GetReportReceiptReportDetailTemp()
        {
            var _clsGetReportDetailTemp = new BllReportReceipt();
            var _dtGetReportDetailTemp =
                _clsGetReportDetailTemp.GetReportReceiptDetailTemp(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetReportDetailTemp != null && _dtGetReportDetailTemp.Rows.Count > 0)
            {
                StoreReportReceipt_Detail.DataSource = _dtGetReportDetailTemp;
                StoreReportReceipt_Detail.DataBind();
            }
            else
            {
                grReportReceipt_Detail.GetStore().RemoveAll();
            }
        }
        private void GetReportReceiptReportDetailTempSum()
        {
            var _clsGetReportDetailTempSum = new BllReportReceipt();
            var _dtGetReportDetailTempSum =
                _clsGetReportDetailTempSum.GetReportReceiptDetailTempSum(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetReportDetailTempSum != null && _dtGetReportDetailTempSum.Rows.Count > 0)
            {
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
                lbPriVATOrderReportReceipt.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Total_VoucherAmount"]).Replace(".", ",");
                lbTotalCostOrderReportReceipt.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
            }
        }
        private void GetReportReceiptReportDetail(int id)
        {
            var _clsGetReportDetail = new BllReportReceipt();
            var _dtGetReportDetail = _clsGetReportDetail.GetReportReceiptDetail(id);
            if (_dtGetReportDetail != null && _dtGetReportDetail.Rows.Count > 0)
            {
                StoreReportReceipt_Detail.DataSource = _dtGetReportDetail;
                StoreReportReceipt_Detail.DataBind();
            }
            else
            {
                grReportReceipt_Detail.GetStore().RemoveAll();
            }
        }
        private void GetReportReceiptReportDetailSum(int id)
        {
            var _clsGetReportDetailSum = new BllReportReceipt();
            var _dtGetReportDetailSum =
                _clsGetReportDetailSum.GetReportReceiptDetailSum(id);
            if (_dtGetReportDetailSum != null && _dtGetReportDetailSum.Rows.Count > 0)
            {
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
                lbPriVATOrderReportReceipt.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Total_VoucherAmount"]).Replace(".", ",");
                lbTotalCostOrderReportReceipt.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
            }
        }
        private void GetReceiptFillterDate()
        {
            try
            {
                var _clsReceip = new BllReceipt();
                if (String.IsNullOrEmpty(txtDateBeginReceiptFillter.Text) && String.IsNullOrEmpty(txtDateEndReceiptFillter.Text))
                {
                    var _dtGetReceipt = _clsReceip.GetReceiptReport(txtSearch.Text);
                    if (_dtGetReceipt != null && _dtGetReceipt.Rows.Count > 0)
                    {
                        StoreReportReceiptOrder.DataSource = _dtGetReceipt;
                        StoreReportReceiptOrder.DataBind();
                    }
                    else
                    {
                        grReceipt.GetStore().RemoveAll();
                    }
                }
                else
                {
                    var _dtGetReceipt = _clsReceip.GetReceiptReportFillterDate(txtDateBeginReceiptFillter.Text, txtDateEndReceiptFillter.Text);
                    if (_dtGetReceipt != null && _dtGetReceipt.Rows.Count > 0)
                    {
                        StoreReportReceiptOrder.DataSource = _dtGetReceipt;
                        StoreReportReceiptOrder.DataBind();
                    }
                    else
                    {
                        grReceipt.GetStore().RemoveAll();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình lọc dữ liệu <br/>" + ex.Message);
            }
        }
        private void GetReceiptFillterDateMain()
        {
            try
            {
                var _clsReceip = new BllReportReceipt();
                if (String.IsNullOrEmpty(txtDateBeginFillter.Text) && String.IsNullOrEmpty(txtDateEndFillter.Text))
                {
                    var _dtGetReceipt = _clsReceip.GetReportReceipt(txtSearch.Text);
                    if (_dtGetReceipt != null && _dtGetReceipt.Rows.Count > 0)
                    {
                        StoreReportReceipt.DataSource = _dtGetReceipt;
                        StoreReportReceipt.DataBind();
                    }
                    else
                    {
                        grReportReceipt.GetStore().RemoveAll();
                    }
                }
                else
                {
                    var _dtGetReceiptFillter = _clsReceip.GetReportReceiptFillter(txtDateBeginFillter.Text, txtDateEndFillter.Text);
                    if (_dtGetReceiptFillter != null && _dtGetReceiptFillter.Rows.Count > 0)
                    {
                        StoreReportReceipt.DataSource = _dtGetReceiptFillter;
                        StoreReportReceipt.DataBind();
                    }
                    else
                    {
                        grReportReceipt.GetStore().RemoveAll();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình lọc dữ liệu <br/>" + ex.Message);
            }
        }
        private void GetReceipt()
        {
            var _clsReceipt = new BllReceipt();
            var _dtReceipt = _clsReceipt.GetReceiptReport(string.Empty);
            if (_dtReceipt != null && _dtReceipt.Rows.Count > 0)
            {
                StoreReportReceiptOrder.DataSource = _dtReceipt;
                StoreReportReceiptOrder.DataBind();
            }
            else
            {
                grReceipt.GetStore().RemoveAll();
            }
        }
        private void GetAutoID()
        {
            var _clsCreateCode = new BllCreateCode();
            var _dtGetAutoID = _clsCreateCode.GetAutoID("ReportReceipt_Code", "Report_Receipt");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtReportReceiptCode.Text = "BC.0000" +
                                      Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                       int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsCheck = new BllReportReceipt();
            var dtCheck = _clsCheck.GetReportReceipt(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (txtReportReceipt_ID.Text != dr["ReportReceipt_ID"].ToString())
                    {
                        if (txtReportReceiptCode.Text == dr["ReportReceipt_Code"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã báo cáo này đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                UpdateValue();
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var _clsGetReportDetailTempCheck = new BllReportReceipt();
                    var _dtGetReportDetailTempCheck =
                        _clsGetReportDetailTempCheck.GetReportReceiptDetailTemp(int.Parse(Session["Users_Id"].ToString()));
                    if (_dtGetReportDetailTempCheck.Rows.Count > 0)
                    {
                        var obj = new EtReportReceipt
                        {
                            ReportReceipt_Code = txtReportReceiptCode.Text,
                            Amount_Total = float.Parse(txtAmount_Total.Text.Replace(",", "").Replace(".", "")),
                            DateCreate = DateTime.Parse(txtDateBegin.Text),
                            Note = txtNote.Text,
                            Lock = true
                        };
                        BllReportReceipt.Insert(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Chốt sổ thành công !");
                        GetReportReceipt();
                        GetReportReceiptReportDetailTemp();
                        GetAutoID();
                        ClearText();
                    }
                    else
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Vui lòng chốt sổ trước khi cập nhật chứng từ !");
                    }
                }
                
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtReportReceipt
                    {
                        ReportReceipt_ID = int.Parse(txtReportReceipt_ID.Text),
                        Note = txtNote.Text
                    };
                    BllReportReceipt.Update(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thay đổi thành thành công !");
                    GetReportReceipt();
                }

            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void InsertDetail()
        {
            try
            {
                var sm = grReceipt.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                {
                    foreach (var row in sm.SelectedRows)
                    {
                        var obj = new EtReportReceiptDetail
                        {
                            ReportReceipt_ID = null,
                            Receipt_ID = int.Parse(row.RecordID),
                            Lock = true,
                            flag = 1,
                            Users_Id = int.Parse(Session["Users_Id"].ToString())
                        };
                        BllReportReceipt.InsertDetail(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm phiếu chi thành công !");
                        WindowReceipt.Close();
                    }
                }
                GetReportReceiptReportDetailTemp();
                GetReportReceiptReportDetailTempSum();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[Clear-Text]
        private void ClearText()
        {
            txtReportReceipt_ID.Text = string.Empty;
            txtDateBegin.Text = DateTime.Now.ToString();
            txtAmount_Total.Text = "0";
            txtNote.Text = string.Empty;
            grReportReceipt_Detail.GetStore().RemoveAll();
            lbPriVATOrderReportReceipt.Text = string.Empty;
            lbTotalCostOrderReportReceipt.Text = string.Empty;
        }
        #endregion
    }
}